<?php

namespace app\admin\controller\kuerp;

use addons\kuerp\model\Collection;
use addons\kuerp\model\Message;
use addons\kuerp\model\OperationLog;
use app\common\controller\Backend;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember;
use app\admin\model\kuerp\CustomersUser;
use app\admin\model\kuerp\Record;
use think\Db;
use Exception;
use think\exception\PDOException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date as PHPExcel_Shared_Date;
use fast\Tree;
/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Customers extends Backend
{

    /**
     * Customers模型对象
     * @var \app\admin\model\kuerp\Customers
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $this->model = new \app\admin\model\kuerp\Customers;
        $this->view->assign("customers", $this->model->getCustomersList());
        $salelist = $this->model->getSaleList();
        $this->view->assign("saleList", $salelist);
        $this->assignconfig("saleList", $salelist);

        $categorylists = collection(model('\app\admin\model\kuerp\Customertype')->where(['status'=>'1'])->field('id,pid,type_name as name')->select())->toArray();
        Tree::instance()->init($categorylists);
        $categorylists = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        $categorylist = array('' => '==请选择==');
        foreach ($categorylists as $k => $v) {
            $categorylist[$v['id']] = $v['name'];
        }
        $this->view->assign('customertype', $categorylist);

        $levellists = collection(model('\app\admin\model\kuerp\Customerlevel')->field('id,name')->select())->toArray();
        $levellist = array('' => '==请选择==');
        foreach ($levellists as $k => $v) {
            $levellist[$v['id']] = $v['name'];
        }
        $this->view->assign('levellists', $levellist);
        $this->view->assign('is_sale', $this->auth->is_sale);//是否销售
        $this->assignconfig('hasExportPermission', $this->auth->check($setData['nowmenu'].'/export') == 1);//是否有导出权限
        $this->view->assign('exclude_admin', $this->auth->is_sale ? $this->auth->id : 0);//是否销售
        
    }

    public function import()
    {
        if ($this->request->isPost()){
            set_time_limit(0);
            ini_set('memory_limit', '512M');
            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
            $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                if ($importHeadType == 'comment') {
                    $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                } else {
                    $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
                }
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $row1 = (string)$currentSheet->getCellByColumnAndRow(1, 1)->getValue();
                $titleRow = $row1 == '基础信息' ? 2 : 1;//标题按当前系统在第二行，其他系统导过来在第一行
                $fields = [];
                for ($currentRow = $titleRow; $currentRow <= $titleRow; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $val = str_replace('*','',$val);
                        $fields[] = (string)trim($val);
                    }
                }

                for ($currentRow = $titleRow+1; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : trim($val);
                    }
                    $row = array_combine($fields, $values);
                    if( !empty($row['余额日期'])){
                        $row['余额日期'] =  strtotime(gmdate('Y-m-d H:i:s',PHPExcel_Shared_Date::excelToTimeStamp($row['余额日期'])));
                    }
                    $row['销售人员'] = !empty($row['负责人']) ? $row['负责人'] : ($row['销售人员'] ?? '');
                    $row['详细地址'] = !empty($row['地址定位']) ? $row['地址定位'] : ($row['详细地址'] ?? '');
                    $row['联系人'] = !empty($row['【联系人】姓名']) ? $row['【联系人】姓名'] : ($row['联系人'] ?? '');
                    $row['职务'] = !empty($row['【联系人】职务']) ? $row['【联系人】职务'] : ($row['职务'] ?? '');
                    $row['手机'] = !empty($row['【联系人】手机']) ? $row['【联系人】手机'] : ($row['手机'] ?? '');
                    $row['客户类别'] = !empty($row['用户类型']) ? $row['用户类型'] : ($row['客户类别'] ?? '');
                    $row['客户等级'] = $row['客户等级'] ?? '';
                    $row['期初应收款'] = $row['期初应收款'] ?? 0;
                    $row['期初预收款'] = $row['期初预收款'] ?? 0;
                    $row['首要联系人'] = $row['首要联系人'] ?? '';
                    $row['前销售人员'] = !empty($row['前负责人']) ? $row['前负责人'] : ($row['前销售人员'] ?? '');
                    $row['协作人'] = $row['协作人'] ?? '';
                    $insert[] = $row;
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
            // var_dump($insert);exit;
            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $cate = [];$level = [];$saler = [];$last_saler = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(empty($insert_v['客户名称']) && empty($insert_v['联系人'])){
                    unset($insert[$insert_k]);
                }else{
                    if(!empty($insert_v['客户类别']) && !in_array($insert_v['客户类别'],$cate)){
                        $cate[] = $insert_v['客户类别'];
                    }
                    if(!empty($insert_v['客户等级']) && !in_array($insert_v['客户等级'],$level)){
                        $level[] = $insert_v['客户等级'];
                    }
                    if(!empty($insert_v['销售人员']) && !in_array($insert_v['销售人员'],$saler)){
                        $saler[] = $insert_v['销售人员'];
                    }
                    if(!empty($insert_v['前销售人员']) && !in_array($insert_v['前销售人员'],$last_saler)){
                        $last_saler[] = $insert_v['前销售人员'];
                    }
                }
            }

            $catelist = Db::name('kuerp_customertype')->where(['type_name'=>['in',$cate]])->column('id','type_name');
            $catename = $catelist ? array_keys($catelist) : [];// Db::name('kuerp_customertype')->where(['type_name'=>['in',$cate]])->column('type_name');
            if(sizeof($catename)!=sizeof($cate)){
                foreach ($cate as $cate_k=>$cate_v){
                    if(!in_array($cate_v,$catename)){
                        $this->error('客户分类'.$cate_v.'不存在，导入失败');
                    }
                }
            }

            $levellist = Db::name('kuerp_customerlevel')->where(['name'=>['in',$level]])->column('id','name');
            $levelname = $levellist ? array_keys($levellist) : [];//Db::name('kuerp_customerlevel')->where(['name'=>['in',$level]])->column('name');
            if(sizeof($levelname)!=sizeof($level)){
                foreach ($level as $level_k=>$level_v){
                    if(!in_array($level_v,$levelname)){
                        $this->error('客户等级'.$level_v.'不存在，导入失败');
                    }
                }
            }

            $salerlist = Db::name('kuerp_staff_member')->where(['name'=>['in',$saler]])->column('id','name');
            $salername = $salerlist ? array_keys($salerlist) : [];//Db::name('kuerp_staff_member')->where(['name'=>['in',$saler]])->column('name');
            if(sizeof($salername)!=sizeof($saler)){
                foreach ($saler as $saler_k=>$saler_v){
                    if(!in_array($saler_v,$salername)){
                        $this->error('昵称为['.$saler_v.']的销售员不存在，导入失败');
                    }
                }
            }
            //前负责人
            $last_salerlist = Db::name('kuerp_staff_member')->where(['name'=>['in',$last_saler]])->column('id','name');
            //获取管理员列表
            $adminlist = Db::name('admin')->where(['status'=>'normal'])->column('id','nickname');
            

            $params = [];
            $nowsp = '';
            $code = [];
            $now_code = [];
            $now_names = [];
            $area_code = [];//地区名=>[id => id, name => name]
            $curcode = '';
            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['客户名称'])){
                    $nowsp = $insert_k;
                    //地区获取
                    $province = $insert_v['省'] ?? '';
                    $city = $insert_v['市'] ?? '';
                    $area = $insert_v['区'] ?? '';
                    $exceladdress = $insert_v['详细地址'] ?? '';
                    if (empty($province) || empty($city) || empty($exceladdress)) {
                        // $this->error('导入失败，'.$insert_k.'省市区及详细地址不能为空');
                    }
                    $province_id = $city_id = $area_id = 0;
                    $province_name = $city_name = $area_name = '';
                    if (!empty($area_code[$province])) {
                        $province_id = $area_code[$province]['id'];
                        $province_name = $area_code[$province]['name'];
                    } else {
                        $provinceinfo = Db::name('area')->where(['name|shortname'=>$province, 'level' => 1])->find();
                        if (empty($provinceinfo)) {
                            // $this->error($insert_k.'行导入失败，省'.$province.'不存在');
                        } else {
                            $province_id = $provinceinfo['id'];
                            $province_name = $provinceinfo['name'];
                            $area_code[$province] = ['id' => $province_id, 'name' => $provinceinfo['name']];
                        }
                    }
                    if (!empty($city)) {
                        if (!empty($area_code[$city])) {
                            $city_id = $area_code[$city]['id'];
                            $city_name = $area_code[$city]['name'];
                        } else {
                            $cityinfo = Db::name('area')->where(['name|shortname'=>$city, 'level' => 2, 'pid' => $province_id])->find();
                            if (empty($cityinfo)) {
                                // $this->error('导入失败，城市'.$city.'不存在');
                            } else {
                                $city_id = $cityinfo['id'];
                                $city_name = $cityinfo['name'];
                                $area_code[$city] = ['id' => $city_id, 'name' => $cityinfo['name']];
                            }
                        }
                    }
                    if (!empty($area)) {
                        if (!empty($area_code[$area])) {
                            $area_id = $area_code[$area]['id'];
                            $area_name = $area_code[$area]['name'];
                        } else {
                            $areainfo = Db::name('area')->where(['name|shortname'=>$area, 'level' => 3, 'pid' => $city_id])->find();
                            if (empty($areainfo)) {
                                // $this->error('导入失败，地区'.$area.'不存在');
                            } else {
                                $area_id = $areainfo['id'];
                                $area_name = $areainfo['name'];
                                $area_code[$area] = ['id' => $area_id, 'name' => $areainfo['name']];
                            }
                        }
                    }
                    // $address = str_replace($province_name.$city_name.$area_name,'',$exceladdress);
                    $address = $exceladdress;
                    
                    if (!empty($insert_v['客户编号'])) {
                        if(in_array($insert_v['客户编号'],$code)){
                            $this->error('导入失败，客户编号'.$insert_v['客户编号'].'重复');
                        }
                        $curcode = $insert_v['客户编号'];
                    } else {
                        $curcode = (new Goods())->getCodes($curcode,1);
                        
                    }
                    $now_code[] = $curcode;
                    $now_names[] = $insert_v['客户名称'];
                    //协作人
                    $collaborators = $insert_v['协作人'] ? explode(',',$insert_v['协作人']) : [];
                    $collaboratorids = [];
                    foreach ($collaborators as $collaborator_k=>$collaborator_v){
                        if(!empty($adminlist[$collaborator_v])){
                            $collaboratorids[] = $adminlist[$collaborator_v];
                        }
                    }
                    $collaboratorids = implode(',',$collaboratorids);
                    
                    $params[$insert_k] = [
                        'customer_code'     => $curcode,
                        'customer_name'     => $insert_v['客户名称'],
                        'customertype_id'   => isset($catelist[$insert_v['客户类别']])?$catelist[$insert_v['客户类别']]:0,
                        'customerlevel_id'  => isset($levellist[$insert_v['客户等级']])?$levellist[$insert_v['客户等级']]:1,
                        'staff_member_id'   => isset($salerlist[$insert_v['销售人员']])?$salerlist[$insert_v['销售人员']]:0,

                        'account_time'      => !empty($insert_v['余额日期'])?$insert_v['余额日期']:time(),
                        'receive_account'   => $insert_v['期初应收款'] ?? '',
                        'opening_prepayment'=> $insert_v['期初预收款'] ?? '',
                        'need_receive_account' => $insert_v['期初应收款'] ? round(((float)$insert_v['期初应收款']-(float)$insert_v['期初预收款']),4) : 0,
                        'identification'    => $insert_v['纳税人识别号'] ?? '',
                        'deposit_bank'      => $insert_v['开户银行'] ?? '',
                        'bank_number'       => $insert_v['银行账号'] ?? '',

                        'connet_name'       => $insert_v['联系人'],
                        'customer_mobile'   => $insert_v['手机'] ?? '',
                        'customer_phone'    => $insert_v['座机'] ?? '',
                        'qq_wx_email'       => $insert_v['QQ/微信'] ?? '',
                        'getgoods_address'  => $insert_v['联系地址'] ?? '',
                        'province_id'       => $province_id,
                        'city_id'           => $city_id,
                        'area_id'           => $area_id,
                        'mergename'         => $province_name.','.$city_name.($area_name ? ','.$area_name : ''),
                        'address'           => $address,
                        'room'              => $insert_v['房号'] ?? '',
                        'last_staff_member_id'=> $insert_v['前销售人员'] && !empty($last_salerlist[$insert_v['前销售人员']]) ? $last_salerlist[$insert_v['前销售人员']] : 0,
                        'collaborator'      => $collaboratorids,

                        'createtime'        => time(),
                        'updatetime'        => time(),
                        'userlist'          =>[],
                        'first'             =>0
                    ];
                }
                if(isset($params[$nowsp]['userlist']) && (!empty($insert_v['联系人']))){
                    $is_first = 0;
                    if($insert_v['首要联系人']=='是' && $params[$nowsp]['first']==0){
                        $is_first = 1;$params[$nowsp]['first'] = 1;
                    }
                    $params[$nowsp]['userlist'][] = [
                        'customers_code'        => $params[$nowsp]['customer_code'],
                        'first_connect_name'    => $insert_v['联系人'],
                        'first_connect_mobile'  => $insert_v['手机'] ?? '',
                        'first_connect_phone'   => $insert_v['座机'] ?? '',
                        'qq_wx_email'           => $insert_v['QQ/微信'] ?? '',
                        'connect_address'       => $insert_v['联系地址'] ?? '',
                        'job'                   => $insert_v['职务'] ?? '',
                        'is_first'              => $is_first,
                        'createtime'            => time(),
                        'updatetime'            => time(),
                    ];
                }
            }

            $editstatus = isset($_POST['editstatus'])?$_POST['editstatus']:1;
            $edit_arr = [];
            if($editstatus==0){
                // $code_s = Db::name('kuerp_customers')->where(['customer_name'=>['in',$now_names]])->value('customer_name');
                // if(!empty($code_s)){
                //     $this->error('导入失败，客户'.$code_s.'已存在');
                // }
            }else{
                $code_list = Db::name('kuerp_customers')->where(['customer_name'=>['in',$now_names]])->column('id','customer_name');
                foreach ($params as $params_k=>$params_v){
                    if(isset($code_list[$params_v['customer_name']])){
                        $params_v['id'] = $code_list[$params_v['customer_name']];
                        $edit_arr[] = $params_v;
                        unset($params[$params_k]);
                    }
                }
            }
            // if($editstatus==0){
            //     $code_s = Db::name('kuerp_customers')->where(['customer_code'=>['in',$now_code]])->value('customer_code');
            //     if(!empty($code_s)){
            //         $this->error('导入失败，客户编号'.$code_s.'已存在');
            //     }
            // }else{
            //     $code_list = Db::name('kuerp_customers')->where(['customer_code'=>['in',$now_code]])->column('id','customer_code');
            //     foreach ($params as $params_k=>$params_v){
            //         if(isset($code_list[$params_v['customer_code']])){
            //             $params_v['id'] = $code_list[$params_v['customer_code']];
            //             $edit_arr[] = $params_v;
            //             unset($params[$params_k]);
            //         }
            //     }
            // }
            Db::startTrans();
            try {
                if(!empty($params)){
                    foreach ($params as $params_k=>$params_v){
                        $userarr = $params_v['userlist'];unset($params_v['userlist']);unset($params_v['first']);
                        $result = Db::name('kuerp_customers')->insertGetId($params_v);

                        $business_type = 5;
                        if($params_v['need_receive_account']>0){//应收
                            Db::name('kuerp_writeoff_source')->insert([
                                'purchase_type' => 5,
                                'type' => 3,
                                'customers_id' => $result,
                                'purchase_code' => $params_v['customer_code'],
                                'purchase_time' => $params_v['account_time'],
                                'price' => $params_v['need_receive_account'],
                                'write_off' => $params_v['need_receive_account'],
                            ]);
                        }else if($params_v['need_receive_account']<0){//预收
                            Db::name('kuerp_writeoff_source')->insert([
                                'purchase_type' => 6,
                                'type' => 3,
                                'customers_id' => $result,
                                'purchase_code' => $params_v['customer_code'],
                                'purchase_time' => $params_v['account_time'],
                                'price' => $params_v['need_receive_account'],
                                'write_off' => $params_v['need_receive_account'],
                            ]);
                            $business_type = 6;
                        }
                        Db::name('kuerp_sales_payment_log')->insert([
                            'customers_id' => $result,
                            'business_type' => $business_type,
                            'bill_time' => $params_v['account_time'],
                            'bill_code' => $params_v['customer_code'],
                            'give_money' => $params_v['need_receive_account'],
                        ]);

                        if(!empty($userarr)){
                            foreach ($userarr as $data_k=>$data_v){
                                $userarr[$data_k]['sid'] = $result;
                            }
                            Db::name('kuerp_customers_user')->insertAll($userarr);
                        }
                    }
                }
                if(!empty($edit_arr)){
                    foreach ($edit_arr as $edit_arr_k=>$edit_arr_v){

                        $business_type = 5;
                        Db::name('kuerp_writeoff_source')->where((new Goods())->setWhere(['customers_id'=>$edit_arr_v['id'],'type'=>3]))->delete();
                        Db::name('kuerp_sales_payment_log')->where((new Goods())->setWhere(['bill_code'=>$edit_arr_v['customer_code'],'business_type'=>['in',[5,6]]]))->delete();
                        if($edit_arr_v['need_receive_account']>0){//应收
                            Db::name('kuerp_writeoff_source')->insert([
                                'purchase_type' => 5,
                                'type' => 3,
                                'customers_id' => $edit_arr_v['id'],
                                'purchase_code' => $edit_arr_v['customer_code'],
                                'purchase_time' => $edit_arr_v['account_time'],
                                'price' => $edit_arr_v['need_receive_account'],
                                'write_off' => $edit_arr_v['need_receive_account'],
                            ]);
                        }else if($edit_arr_v['need_receive_account']<0){//预收
                            Db::name('kuerp_writeoff_source')->insert([
                                'purchase_type' => 6,
                                'type' => 3,
                                'customers_id' => $edit_arr_v['id'],
                                'purchase_code' => $edit_arr_v['customer_code'],
                                'purchase_time' => $edit_arr_v['account_time'],
                                'price' => $edit_arr_v['need_receive_account'],
                                'write_off' => $edit_arr_v['need_receive_account'],
                            ]);
                            $business_type = 6;
                        }
                        Db::name('kuerp_sales_payment_log')->insert([
                            'customers_id' => $edit_arr_v['id'],
                            'business_type' => $business_type,
                            'bill_time' => $edit_arr_v['account_time'],
                            'bill_code' => $edit_arr_v['customer_code'],
                            'give_money' => $edit_arr_v['need_receive_account'],
                        ]);

                        $userarr = $edit_arr_v['userlist'];unset($edit_arr_v['userlist']);unset($edit_arr_v['first']);
                        $id = $edit_arr_v['id'];
                        unset($edit_arr_v['createtime']);unset($edit_arr_v['id']);
                        $result = (new \app\admin\model\kuerp\Customers())->where((new Goods())->setWhere(['id'=>$id]))->update($edit_arr_v);
                        Db::name('kuerp_customers_user')->where((new Goods())->setWhere(['sid'=>$id]))->delete();
                        if(!empty($userarr)){
                            foreach ($userarr as $data_k=>$data_v){
                                $userarr[$data_k]['sid'] = $id;
                            }
                            Db::name('kuerp_customers_user')->insertAll($userarr);
                        }
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success(['update'=>sizeof($edit_arr),'add'=>sizeof($params)]);
        }
        $this->assign('time', time());
        return $this->view->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $sale_users = [];
        if (!$this->auth->isSuperAdmin()) {
            //部门经理查看部门成员 上级部门能查看下级部门
            $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
            //转为职员id
            if ($adminids) {
                $sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            }
            $this->view->assign("searchsaleList", (new StaffMember())->getSaleList($sale_users));
        } else {
            $this->view->assign("searchsaleList", $this->model->getSaleList());
        }
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $wheres = [];
            $type = $this->request->get("type/d");//1仅本人
            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            if (isset($filter['customer_mobile'])) {
                // 自定义处理
                $customer_mobile = $filter['customer_mobile'];
                // 处理完可以去掉也可以覆盖重构
                unset($filter['customer_mobile'],$op['customer_mobile']);
                $sids = Db::name('kuerp_customers_user')->where(['first_connect_mobile'=>['like', '%'.$customer_mobile.'%']])->column('sid');
                $wheres['customers.id'] = ['in',$sids];
            }
            $this->request->get(['filter'=>json_encode($filter,true)]);
            $this->request->get(['op'=>json_encode($op,true)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $data = input();
            
            if(isset($data['keywords'])){
                $wheres['customers.status'] = '1';
                $wheres['customers.customer_name'] = ['like', '%'.$data['keywords'].'%'];
            }
            if (isset($data['createtime'])) {
                $createtime = str_replace(' - ', ',', $data['createtime']);
                $arr = array_slice(explode(',', $createtime), 0, 2);
                $wheres['customers.createtime'] = ['between time', $arr];
            }
            if (!$this->auth->isSuperAdmin()) {
                $where1 = [];
                if ($this->auth->is_sale) {
                    $where1['customers.staff_member_id'] = $this->auth->staff_member_id;
                    $wheres['customers.staff_member_id'] = ['exp', Db::raw(' ='.$this->auth->staff_member_id.'  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                }
                //转为职员id
                if ($sale_users) {
                    // $sale_users[] = 0;
                    $where1['customers.staff_member_id'] = ['in',$sale_users];
                    $wheres['customers.staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                } else {
                    $where1['customers.staff_member_id'] = -1;
                    $wheres['customers.staff_member_id'] = ['exp', Db::raw(' =-1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                }
                if ($type == 1) {
                    $wheres['customers.staff_member_id'] = $where1['customers.staff_member_id'];
                }
            }
            $list = $this->model
                ->with(['customertype','customerlevel','saler'])
                ->where($where)->where($wheres)
                // ->order($sort, $order)
                ->order('id DESC,staff_member_id asc')
                ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('customerlevel')->visible(['name']);
                $row->getRelation('customertype')->visible(['type_name']);
                $row->getRelation('saler')->visible(['name']);
            }
            //获取协作人员
            $adminlist = Db::name('admin')->column('nickname', 'id');
            foreach ($list as $key => $value) {
                $collaborators = $value['collaborator'] ? explode(',', $value['collaborator']) : [];
                $collaborators_name = [];
                foreach ($collaborators as $k => $v) {
                    $collaborators_name[] = $adminlist[$v];
                }
                $list[$key]['collaborators_name'] = implode(';', $collaborators_name);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 导出信息
     */
    public function export()
    {
        $param = $this->request->param();
        if (isset($param['user_path'])) {
            if (file_exists($_SERVER['DOCUMENT_ROOT'].$param['user_path'])) {
                unlink($_SERVER['DOCUMENT_ROOT'].$param['user_path']); // 删除文件
            }
            exit();
        }
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $ids = $param['ids'];
        $isall = $param['isall'];
        $wheres = [];
        if($isall != 3 && empty($ids)){
            $this->error(__('请选择要导出的数据'));
        }
        //导出其中几条
        if (isset($ids) ) {
            $wheres['customers.id'] = array('in', $ids);
        }
        //导出全部
        if (isset($isall)) {
            if ($isall == 3) {
                unset($wheres['customers.id']);
            }
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $sale_users = [];
        if (!$this->auth->isSuperAdmin()) {
            //部门经理查看部门成员 上级部门能查看下级部门
            $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
            //转为职员id
            if ($adminids) {
                $sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            }
        }

        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        $filter = json_decode($this->request->get("filter", ''), true);
        $op = json_decode($this->request->get("op", '','trim'), true);
        if (isset($filter['customer_mobile'])) {
            // 自定义处理
            $customer_mobile = $filter['customer_mobile'];
            // 处理完可以去掉也可以覆盖重构
            unset($filter['customer_mobile'],$op['customer_mobile']);
            $sids = Db::name('kuerp_customers_user')->where(['first_connect_mobile'=>['like', '%'.$customer_mobile.'%']])->column('sid');
            $wheres['customers.id'] = ['in',$sids];
        }
        $this->request->get(['filter'=>json_encode($filter,true)]);
        $this->request->get(['op'=>json_encode($op,true)]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $data = input();

        if(isset($data['keywords'])){
            $wheres['customers.status'] = '1';
            $wheres['customers.customer_name'] = ['like', '%'.$data['keywords'].'%'];
        }
        if (!$this->auth->isSuperAdmin()) {
            if ($this->auth->is_sale) {
                // $wheres['customers.staff_member_id'] = ['in', [0, $this->auth->staff_member_id]];
                $wheres['customers.staff_member_id'] = ['exp', Db::raw(' in (0, '.$this->auth->staff_member_id.')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            }
            //转为职员id
            if ($sale_users) {
                $sale_users[] = 0;
                $wheres['customers.staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            } else {
                $wheres['customers.staff_member_id'] = ['exp', Db::raw(' =-1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            }
        }
        $list = $this->model
            ->with(['customertype','customerlevel','saler','customersuser'])
            ->where($where)->where($wheres)
            ->order('id DESC,staff_member_id asc')
            ->select();

        foreach ($list as $row) {
            $row->getRelation('customerlevel')->visible(['name']);
            $row->getRelation('customertype')->visible(['type_name']);
            $row->getRelation('saler')->visible(['name']);
            $row->getRelation('customersuser')->visible(['customers_code','first_connect_name','first_connect_mobile','first_connect_phone','job','qq_wx_email','is_first','createtime']);
        }
        //获取协作人员
        $adminlist = Db::name('admin')->column('nickname', 'id');
        foreach ($list as $key => $value) {
            $collaborators = $value['collaborator'] ? explode(',', $value['collaborator']) : [];
            $collaborators_name = [];
            foreach ($collaborators as $k => $v) {
                $collaborators_name[] = $adminlist[$v];
            }
            $list[$key]['collaborators_name'] = implode(';', $collaborators_name);
        }

        $list = collection($list)->toArray();

    //    dump($list);exit();
        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '客户名称',
            '客户编号',
            '分类名称',
            '客户等级',
            '销售人员',
            '地区',
            '地址',
            '房号',
            '协作人',
            '最后跟进时间',
            '备注',
            '创建时间',
            '联系人名称',
            '手机号',
            '座机',
            '职务',
            'QQ/微信/Email',
            '首要联系人',
            '创建时间',
        ];

        $userinfo = [];
        foreach ($list as $k => $v) {
            $field1 = array(
                $v['customer_name'] ?? '',
                $v['customer_code'] ?? '',
                $v['customertype']['type_name'] ?? '',
                $v['customerlevel']['name'] ?? '',
                $v['saler']['name'] ?? '',
                $v['mergename'] ?? '',
                $v['address'] ?? '',
                $v['room'] ?? '',
                $v['collaborators_name'] ?? '',
                $v['last_follow_time'] ? date('Y-m-d H:i:s',$v['last_follow_time']) : '',
                $v['note'] ?? '',
                date('Y-m-d H:i:s',$v['createtime']),
            );

            $field2 = array(
                $v['customersuser']['first_connect_name'] ?? '',
                $v['customersuser']['first_connect_mobile'] ?? '',
                $v['customersuser']['first_connect_phone'] ?? '',
                $v['customersuser']['job'] ?? '',
                $v['customersuser']['qq_wx_email'] ?? '',
                $v['customersuser']['createtime'] == 1 ? '是' : '否',
                date('Y-m-d H:i:s', $v['customersuser']['createtime']),
            );

            if(isset($userinfo[$v['customer_code']])){
                $field1 = array_fill(0, count($field1), '');
            }
            $field = array_merge($field1, $field2);
            $userinfo[$v['customer_code']] =  $v['customer_code'];
            $datainfo[] = $field;
        }

        $file = export_excel($title, $datainfo, '客户');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }

    /**
     * 客户详情
     */
    public function detail($ids = null)
    {
        $type = $this->request->param("type",'');
        $customerid = $this->request->param("id",'');
        $limit = $this->request->param("limit",'10');
        if($type == 'record'){
            $list = Record::getList(Record::CUSTOMER_TYPE, $customerid);
            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }elseif ($type == 'contacts'){
            $list = (new \app\admin\model\kuerp\CustomersUser())->where(['sid'=>$customerid])->select();
            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }elseif ($type == 'goods_sales'){
            $list = (new \app\admin\model\kuerp\GoodsSales())
                ->with(['customers','preparation','examine'])
                ->where(['goods_sales.customers_id'=>$customerid])
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('customers')->visible(['customer_name']);
                $row->getRelation('preparation')->visible(['username', 'nickname']);
                $row->getRelation('examine')->visible(['username', 'nickname']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }elseif($type == 'collection'){
            $list = Collection::with(['admin','staffmember','collectionsale'])->where(['customers_id'=>$customerid])->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['username', 'nickname']);
                $row->getRelation('staffmember')->visible(['name']);
            }

            $lists = [];
            $moneys = 0;$write_off = 0;
            $customers_list = [];
            $admin_list = [];
            if ($list) {
                $customers_list = Db::name('kuerp_customers')->where(['id'=>['in', array_column($list->items(), 'customers_id')]])->column('customer_name', 'id');
                $admin_list = Db::name('admin')->where(['id'=>['in', array_column($list->items(), 'examine_id')]])->column('username,nickname', 'id');
            }
            foreach ($list as $list_k=>$list_v){
                if(isset($list_v['print_num']) && empty($list_v['print_num'])){
                    $list_v['print_num'] = 0;
                }
                $customers = $customers_list[$list_v['customers_id']] ?? '';//Db::name('kuerp_customers')->where(['id'=>$list_v['customers_id']])->value('customer_name');
                $staff_member = $list_v['staffmember']['name'];//Db::name('kuerp_staff_member')->where(['id'=>$list_v['staff_member_id']])->value('name');
                $preparation = $list_v['admin']['nickname'];//Db::name('admin')->where(['id'=>$list_v['preparation_id']])->value('username');
                $examine =  $admin_list[$list_v['examine_id']]['nickname'] ?? '';//Db::name('admin')->where(['id'=>$list_v['examine_id']])->value('username');

                $account = Db::name('kuerp_collection_account')->alias('co')
                    ->join('kuerp_accounts a','a.id=co.accounts_id')
                    ->join('kuerp_settlementtype s','s.id=co.settlementtype','left')
                    ->where((new Goods())->setWhere(['co.collection_id'=>$list_v['id']]))
                    ->field('co.money,a.account_name,s.name,co.number,co.remark')
                    ->select();
                foreach ($account as $account_k=>$account_v){
                    $lists[] = [
                        'id'            => $list_v['id'],
                        'purchase_code' => $list_v['purchase_code'],
                        'purchase_time' => date('Y-m-d',$list_v['purchase_time']),
                        'customers_id'  => $customers,
                        'accounts_id'   => $account_v['account_name'],
                        'money'         => $account_v['money'],
                        'settlementtype'=> $account_v['name'],
                        'number'        => $account_v['number'],
                        'remark'        => $account_v['remark'],
                        'moneys'        => $list_v['money'],
                        'write_off'     => $list_v['write_off'],
                        'discount'      => $list_v['discount'],
                        'advance'       => $list_v['advance'],
                        'staff_member'  => $staff_member,
                        'examine'       => $examine,
                        'preparation'   => $preparation,
                        'remarks'       => $list_v['remarks'],
                        'print_num'     => $list_v['print_num'],
                        'createtime'    => date('Y-m-d H:i', $list_v['createtime']),
                    ];
                }
            }
            $result = array("total" => $list->total(), "rows" => $lists);
            return json($result);
        }elseif ($type == 'operation_log'){
            //操作记录
            $log=OperationLog::getList(OperationLog::CUSTOMER_TYPE, $customerid);
            $result = array("total" => count($log), "rows" => $log);
            return json($result);
        }elseif ($type == 'sign'){
            $list = (new \app\admin\model\kuerp\StaffSignIn())
                ->with(['customers', 'staffmember'])
                ->where(['customer_id'=>$customerid])
                ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('customers')->visible(['customer_name']);
                $row->getRelation('staffmember')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $row = $this->model->with([
            'saler',
            'customertype',
            'customerlevel',
        ])->where([
            'customers.id' => $ids,
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $sale_users = [];
        if (!$this->auth->isSuperAdmin()) {
            //部门经理查看部门成员 上级部门能查看下级部门
            $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
            //转为职员id
            if ($adminids) {
                $sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            }
        }
        $row['operation_team'] = 'read';
        if ($this->auth->isSuperAdmin() || $row['staff_member_id'] == $this->auth->staff_member_id || in_array($row['staff_member_id'],$sale_users ?? []) || in_array($this->auth->id, explode(',', $row['collaborator']))) {
            $row['operation'] = 'update';//修改权限
            $row['is_operation'] = 1;
        } else {
            $row['operation'] = 'read';//只读权限
            $row['is_operation'] = 0;
        }
        if (!$this->auth->isSuperAdmin() && $this->auth->staff_member_id > 0 && $row['staff_member_id'] != $this->auth->staff_member_id && !in_array($row['staff_member_id'],$sale_users) && !in_array($this->auth->id, explode(',', $row['collaborator']))) {
            $this->error('抱歉，您没有权限查看该客户信息');
        }
        $row['collaborator'] = implode('/',Db::name('admin')->whereIn('id', $row['collaborator'])->column('nickname'));
        //标记通知已读
        Message::setRead(Message::CUSTOMER_TYPE, $ids, $this->auth->id);
//        $this->assign('records', Record::getList(Record::CUSTOMER_TYPE, $ids));
        $row['createtime'] = date('Y-m-d', $row['createtime']);
        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $this->assignconfig("idinfo", ['id' => $ids, 'operation' => $row['operation']]);
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $params['account_time'] = strtotime($params['account_time']);
                $params['need_receive_account'] = round(((float)$params['receive_account']-(float)$params['opening_prepayment']),4);
                if (!empty($params['area_id'])) {
                    $areainfo = Db::name('area')->find($params['area_id']);
                    $params['mergename'] = str_replace('中国,', '', $areainfo['mergename']);
                }

                $data = [];
                $user = $this->request->post("user/a");
                if(empty($user['first'])){
                    $this->error('请填写联系人');
                }else{
                    $default = '';
                    foreach ($user['first'] as $user_first_k=>$user_first_v){
                        if(isset($user['name'][$user_first_k]) && !empty($user['name'][$user_first_k])){
                            if($user_first_v==1 && $default!==''){
                                $this->error('只能选择一个首要联系人');
                            }
                            if (empty($user['mobile'][$user_first_k])) {
                                $this->error('联系人手机号不能为空');
                            }
                            if (preg_match('/^1\d{10}$/', $user['mobile'][$user_first_k]) ==false) {
                                $this->error('手机号格式错误');
                            }
                            
                            if($user_first_v==1){
                                $default = $user_first_k;
                            }
                            $data[] = [
                                'first_connect_name' => $user['name'][$user_first_k],
                                'first_connect_mobile' => $user['mobile'][$user_first_k],
                                'first_connect_phone' => $user['phone'][$user_first_k],
                                'qq_wx_email' => $user['qqnum'][$user_first_k],
                                'job' => $user['job'][$user_first_k],
                                'connect_address' => $user['address'][$user_first_k],
                                'is_first' => $user['first'][$user_first_k],
                                'createtime' => time(),
                                'updatetime' => time(),
                            ];
                        }
                    }
                    if(empty($data)){
                        $this->error('请完善联系人信息');
                    }
                }
                $default = $default===''?0:$default;
                $data[$default]['is_first'] = 1;
                $params['connet_name'] = $user['name'][$default];
                $params['customer_mobile'] = isset($user['mobile'][$default])?$user['mobile'][$default]:'';
                $params['customer_phone'] = isset($user['phone'][$default])?$user['phone'][$default]:'';
                $params['qq_wx_email'] = isset($user['qqnum'][$default])?$user['qqnum'][$default]:'';
                $params['getgoods_address'] = isset($user['address'][$default])?$user['address'][$default]:'';

                if(Db::name('kuerp_customers')->where((new Goods())->setWhere(['customer_code'=>trim($params['customer_code'])]))->find()){
                    $this->error('客户编号已占用');
                }
                if ($this->auth->staff_member_id) {
                    $params['staff_member_id'] = $this->auth->staff_member_id;
                }
                //判断客户名称是否重复
                $count = Db::name('kuerp_customers')->where(['customer_name' => $params['customer_name'], 'staff_member_id' => $params['staff_member_id'], 'status' => '1'])->count();
                if ($count) {
                    $this->error($params['customer_name'].'客户已存在');
                }

                $result = false;
                Db::startTrans();
                try {
                    
                    $params['createtime'] = time();$params['updatetime'] = time();
                    $result = Db::name('kuerp_customers')->insertGetId($params);
                    $business_type = 5;
                    if($params['need_receive_account']>0){//应收
                        Db::name('kuerp_writeoff_source')->insert([
                            'purchase_type' => 5,
                            'type' => 3,
                            'customers_id' => $result,
                            'purchase_code' => $params['customer_code'],
                            'purchase_time' => $params['account_time'],
                            'price' => $params['need_receive_account'],
                            'write_off' => $params['need_receive_account'],
                            'remark' => $params['note'],
                        ]);
                    }else if($params['need_receive_account']<0){//预收
                        Db::name('kuerp_writeoff_source')->insert([
                            'purchase_type' => 6,
                            'type' => 3,
                            'customers_id' => $result,
                            'purchase_code' => $params['customer_code'],
                            'purchase_time' => $params['account_time'],
                            'price' => -$params['need_receive_account'],
                            'write_off' => -$params['need_receive_account'],
                            'remark' => $params['note'],
                        ]);
                        $business_type = 6;
                    }
                    Db::name('kuerp_sales_payment_log')->insert([
                        'customers_id' => $result,
                        'business_type' => $business_type,
                        'bill_time' => $params['account_time'],
                        'bill_code' => $params['customer_code'],
                        'give_money' => $params['need_receive_account'],
                    ]);

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['customers_code'] = trim($params['customer_code']);
                        $data[$data_k]['sid'] = $result;
                    }
                    Db::name('kuerp_customers_user')->insertAll($data);
                    if ($this->auth->parentids && !in_array(2, $this->auth->group_ids)) {
                        $content = $this->auth->nickname . "刚刚新建了客户《{$params['customer_name']}》,请您审阅！";
                        foreach ($this->auth->parentids as $k=>$v){
                            Message::addMessage(Message::CUSTOMER_TYPE, $result, $v, $this->auth->id, $content);
                        }
                    }
                    //发送通知
                    $collaborator = explode(',', $params['collaborator']);
                    $content = $this->auth->nickname . "刚刚将您添加为客户《{$params['customer_name']}》的协作人，请知悉";
                    foreach ($collaborator as $v) {
                        Message::addMessage(Message::CUSTOMER_TYPE, $result, $v, $this->auth->id, $content);
                    }
                    
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $code = (new Goods())->getCodes('',1);
        $this->view->assign("code", $code);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $dbuser = (new \app\admin\model\kuerp\CustomersUser())->where(['sid'=>$ids])->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $params['account_time'] = strtotime($params['account_time']);
                $params['need_receive_account'] = $row['need_receive_account'] - ($row['receive_account']-$row['opening_prepayment']) + ((float)$params['receive_account']-(float)$params['opening_prepayment']);
                if (!empty($params['area_id'])) {
                    $areainfo = Db::name('area')->find($params['area_id']);
                    $params['mergename'] = str_replace('中国,', '', $areainfo['mergename']);
                }
                $data = [];
                $user = $this->request->post("user/a");
                if(empty($user['first'])){
                    $this->error('请填写联系人');
                }else{
                    $default = '';
                    foreach ($user['first'] as $user_first_k=>$user_first_v){
                        if(isset($user['name'][$user_first_k]) && !empty($user['name'][$user_first_k])){
                            if($user_first_v==1 && $default!==''){
                                $this->error('只能选择一个首要联系人');
                            }
                            if (empty($user['mobile'][$user_first_k])) {
                                $this->error('联系人手机号不能为空');
                            }
                            if (preg_match('/^1\d{10}$/', $user['mobile'][$user_first_k]) ==false) {
                                $this->error('手机号格式错误');
                            }
                            if($user_first_v==1){
                                $default = $user_first_k;
                            }
                            $userdata = [
                                'first_connect_name' => $user['name'][$user_first_k],
                                'first_connect_mobile' => $user['mobile'][$user_first_k],
                                'first_connect_phone' => $user['phone'][$user_first_k],
                                'qq_wx_email' => $user['qqnum'][$user_first_k],
                                'job' => $user['job'][$user_first_k],
                                'connect_address' => $user['address'][$user_first_k],
                                'is_first' => $user['first'][$user_first_k],
                                'createtime' => time(),
                                'updatetime' => time(),
                            ];
                            if (!empty($user['id'][$user_first_k])) {
                                $userdata['id'] = $user['id'][$user_first_k];
                                unset($userdata['createtime']);
                            }
                            $data[] = $userdata;
                        }
                    }
                    if(empty($data)){
                        $this->error('请完善联系人信息');
                    }
                }
                //联系人对比不存在的删除
                $diff_user = array_diff(array_column($dbuser, 'id'), $user['id']);
                $default = $default===''?0:$default;
                $data[$default]['is_first'] = 1;
                $params['connet_name'] = $user['name'][$default];
                $params['customer_mobile'] = isset($user['mobile'][$default])?$user['mobile'][$default]:'';
                $params['customer_phone'] = isset($user['phone'][$default])?$user['phone'][$default]:'';
                $params['qq_wx_email'] = isset($user['qqnum'][$default])?$user['qqnum'][$default]:'';
                $params['getgoods_address'] = isset($user['address'][$default])?$user['address'][$default]:'';
                if (!empty($params['staff_member_id']) && $params['staff_member_id']!==$row['staff_member_id']) {
                    $params['last_staff_member_id'] = $row['staff_member_id'];
                }

                if(Db::name('kuerp_customers')->where(['customer_code'=>trim($params['customer_code']),'id'=>['<>',$ids]])->find()){
                    $this->error('客户编号已占用');
                }
                $WriteoffSource = Db::name('kuerp_writeoff_source')->where(['customers_id'=>$row['id'],'type'=>3])->value('price');
                if(((float)$row['receive_account']-(float)$row['opening_prepayment'])==$WriteoffSource && ((float)$row['receive_account']-(float)$row['opening_prepayment'])!=((float)$params['receive_account']-(float)$params['opening_prepayment'])){
                    $order = Db::name('kuerp_writeoff')->where(['customers_id|customers_out_id|customers_enter_id'=>$row['id']])->find();
                    if($order){
                        return ['status'=>400,'msg'=>'已关联核销单，不可编辑金额'];
                    }
                }
                //判断协作人是否有更改
                $collaborator_msgid = [];
                if($params['collaborator']!==$row['collaborator']){
                    $new_collaborator = explode(',',$params['collaborator']);
                    $old_collaborator = explode(',',$row['collaborator']);
                    //获取 差集
                    $collaborator_msgid = array_diff($new_collaborator,$old_collaborator);
                }
                $result = false;
                Db::startTrans();
                try {
                    // Db::name('kuerp_customers_user')->where((new Goods())->setWhere(['sid'=>$ids]))->delete();
                    $params['updatetime'] = time();
                    $result = Db::name('kuerp_customers')->where((new Goods())->setWhere(['id'=>$ids]))->update($params);

                    $WriteoffSource = Db::name('kuerp_writeoff_source')->where(['customers_id'=>$ids,'type'=>3])->find();
                    $PaymentLog = Db::name('kuerp_sales_payment_log')->where(['bill_code'=>$row['customer_code'],'business_type'=>['in',[5,6]]])->find();
                    $params['need_receive_account'] = ((float)$params['receive_account']-(float)$params['opening_prepayment']);
                    if($WriteoffSource){
                        $business_type = 5;
                        if($params['need_receive_account']>0){//应收
                            Db::name('kuerp_writeoff_source')->where(['id'=>$WriteoffSource['id']])->update([
                                'purchase_type' => 5,
                                'type' => 3,
                                'customers_id' => $ids,
                                'purchase_code' => $params['customer_code'],
                                'purchase_time' => $params['account_time'],
                                'price' => $params['need_receive_account'],
                                'write_off' => $params['need_receive_account'],
                                'remark' => $params['note'],
                            ]);
                        }else if($params['need_receive_account']<0){//预收
                            Db::name('kuerp_writeoff_source')->where(['id'=>$WriteoffSource['id']])->update([
                                'purchase_type' => 6,
                                'type' => 3,
                                'customers_id' => $ids,
                                'purchase_code' => $params['customer_code'],
                                'purchase_time' => $params['account_time'],
                                'price' => -$params['need_receive_account'],
                                'write_off' => -$params['need_receive_account'],
                                'remark' => $params['note'],
                            ]);
                            $business_type = 6;
                        }
                        Db::name('kuerp_sales_payment_log')->where(['id'=>$PaymentLog['id']])->update([
                            'customers_id' => $ids,
                            'business_type' => $business_type,
                            'bill_time' => $params['account_time'],
                            'bill_code' => $params['customer_code'],
                            'give_money' => $params['need_receive_account'],
                        ]);
                    }else{
                        $business_type = 5;
                        if($params['need_receive_account']>0){//应收
                            Db::name('kuerp_writeoff_source')->insert([
                                'purchase_type' => 5,
                                'type' => 3,
                                'customers_id' => $ids,
                                'purchase_code' => $params['customer_code'],
                                'purchase_time' => $params['account_time'],
                                'price' => $params['need_receive_account'],
                                'write_off' => $params['need_receive_account'],
                                'remark' => $params['note'],
                            ]);
                        }else if($params['need_receive_account']<0){//预收
                            Db::name('kuerp_writeoff_source')->insert([
                                'purchase_type' => 6,
                                'type' => 3,
                                'customers_id' => $ids,
                                'purchase_code' => $params['customer_code'],
                                'purchase_time' => $params['account_time'],
                                'price' => -$params['need_receive_account'],
                                'write_off' => -$params['need_receive_account'],
                                'remark' => $params['note'],
                            ]);
                            $business_type = 6;
                        }
                        Db::name('kuerp_sales_payment_log')->insert([
                            'customers_id' => $ids,
                            'business_type' => $business_type,
                            'bill_time' => $params['account_time'],
                            'bill_code' => $params['customer_code'],
                            'give_money' => $params['need_receive_account'],
                        ]);
                    }

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['customers_code'] = trim($params['customer_code']);
                        $data[$data_k]['sid'] = $ids;
                    }
                    (new CustomersUser())->saveAll($data);
                    if ($diff_user) {
                        (new CustomersUser())->where('id', 'in', $diff_user)->delete();
                    }
                    //发送通知
                    foreach ($collaborator_msgid as $v) {
                        $content = $this->auth->nickname . "刚刚将您添加为客户《{$params['customer_name']}》的协作人，请知悉";
                        Message::addMessage(Message::CUSTOMER_TYPE, $ids, $v, $this->auth->id, $content);
                    }
                    // Db::name('kuerp_customers_user')->saveAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        
        $this->view->assign("user", $dbuser);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            foreach ($list as $list_k=>$list_v){
                $order_info = Db::name('kuerp_goods_sales_info')->where(['customers_id'=>$list_v['id']])->field('id')->find();
                if(!empty($order_info)){
                    $this->error('客户'.$list_v['customer_name'].'已有购货单，不可删除');
                }
                $order_info = Db::name('kuerp_goods_sales_exchange_info')->where(['customers_id'=>$list_v['id']])->field('id')->find();
                if(!empty($order_info)){
                    $this->error('客户'.$list_v['customer_name'].'已有购货退货单，不可删除');
                }
                $order_info = Db::name('kuerp_warehouse')->where(['customers_id'=>$list_v['id']])->field('id')->find();
                if(!empty($order_info)){
                    $this->error('客户'.$list_v['customer_name'].'已有其他入库单，不可删除');
                }
                $order_info = Db::name('kuerp_writeoff')->where(['customers_id|customers_out_id|customers_enter_id'=>$list_v['id']])->field('id')->find();
                if(!empty($order_info)){
                    $this->error('客户'.$list_v['customer_name'].'已有核销单，不可删除');
                }
            }

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += Db::name('kuerp_customers')->where(['id'=>$v['id']])->delete();
                    Db::name('kuerp_customers_user')->where(['sid'=>$v['id']])->delete();
                    Db::name('kuerp_writeoff_source')->where((new Goods())->setWhere(['customers_id'=>$v['id'],'type'=>3]))->delete();
                    Db::name('kuerp_sales_payment_log')->where((new Goods())->setWhere(['bill_code'=>$v['customer_code'],'business_type'=>['in',[5,6]]]))->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'customer_name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $sale_users = [];
        if (!$this->auth->isSuperAdmin()) {
            //部门经理查看部门成员 上级部门能查看下级部门
            $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
            //转为职员id
            $sale_users = $adminids ? (new StaffMember())->getStaffMemberIds($adminids) : [];
            $this->model->where('staff_member_id','exp', Db::raw(($sale_users ? ' in ('.implode(',', $sale_users).')' : '= -1').' OR FIND_IN_SET('.$this->auth->id.',collaborator)'));
        }
        
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            if (!$this->auth->isSuperAdmin()) {
                $this->model->where('staff_member_id','exp', Db::raw(($sale_users ? ' in ('.implode(',', $sale_users).')' : '= -1').' OR FIND_IN_SET('.$this->auth->id.',collaborator)'));
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => $item[$primarykey] ?? '',
                        $field      => $item[$field] ?? '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 批量客户转移
     *
     * @return void
     */
    public function changestaff()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $this->request->post('ids');
        $staff_member_id = $this->request->post('staff_member_id');
        $changeorder = $this->request->post('changeorder');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        if (empty($staff_member_id)) {
            $this->error(__('新负责人不能为空！'));
        }
        $staff_memberinfo = Db::name('kuerp_staff_member')->where('status', '1')->where('id', $staff_member_id)->find();
        if (!$staff_memberinfo) {
            $this->error(__('新负责人不存在！'));
        }
        $list = $this->model->where('id', 'in', $ids)->column('*', 'id');
        if (count($list) != count(explode(',', $ids))) {
            $this->error(__('客户信息错误'));
        }
        $staffList = Db::name('kuerp_staff_member')->where('id', 'in', array_unique(array_column($list, 'staff_member_id')))->column('admin_id', 'id');
        $result = false;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                if ($v['staff_member_id'] == $staff_member_id) continue;
                $result = Db::name('kuerp_customers')->where(['id'=>$v['id']])->update(['staff_member_id' => $staff_member_id,'last_staff_member_id' => $v['staff_member_id'], 'updatetime' => time()]);
                $order_ids = [];
                if ($changeorder) {
                    $order_ids = Db::name('kuerp_goods_sales')->where(['customers_id'=>$v['id']])->column('id');
                    Db::name('kuerp_goods_sales')->where(['customers_id'=>$v['id']])->update(['sale_user' => $staff_member_id,'sale_user_name' => $staff_memberinfo['name'], 'operation_id' => $staff_memberinfo['admin_id'], 'updatetime' => time()]);
                    Db::name('kuerp_goods_sales_info')->where(['customers_id'=>$v['id']])->update(['sale_user' => $staff_member_id,'sale_user_name' => $staff_memberinfo['name'], 'operation_id' => $staff_memberinfo['admin_id'], 'updatetime' => time()]);
                    Db::name('kuerp_goods_sales_summary')->where(['customers_id'=>$v['id']])->update(['sale_user' => $staff_member_id,'sale_user_name' => $staff_memberinfo['name'], 'operation_id' => $staff_memberinfo['admin_id'], 'updatetime' => time()]);
                    // Db::name('kuerp_sales_payment_log')->where(['customers_id'=>$v['id']])->update(['sale_user' => $staff_member_id,'sale_user_name' => $staff_memberinfo['name'], 'operation_id' => $staff_memberinfo['admin_id']]);
                }
                $transfer = [
                    'admin_id' => $this->auth->id,
                    'customers_id' => $v['id'],
                    'old_staff_member_id' => $v['staff_member_id'],
                    'staff_member_id' => $staff_member_id,
                    'ischangeorder' => $changeorder,
                    'order_ids' => implode(',', $order_ids),
                    'createtime' => time(),
                ];
                Db::name('kuerp_customers_transfer')->insert($transfer);
                Db::name('kuerp_sales_payment_log')->where((new Goods())->setWhere(['bill_code'=>$v['customer_code'],'business_type'=>['in',[5,6]]]))->delete();

                //发送通知
                if (!$this->auth->staff_member_id || $this->auth->staff_member_id != $staff_member_id) {
                    $content = $this->auth->nickname . "刚刚将客户《{$v['customer_name']}》".($changeorder ? '及客户相关订单' : '')."转移给您，请知悉";
                    Message::addMessage(Message::CUSTOMER_TYPE, $v['id'], $staff_memberinfo['admin_id'], $this->auth->id, $content);
                }
                
                if(!$this->auth->staff_member_id || $this->auth->staff_member_id != $v['staff_member_id']) {
                    $content = $this->auth->nickname . "刚刚将您的客户《{$v['customer_name']}》".($changeorder ? '及客户相关订单' : '')."转移给了".$staff_memberinfo['name']."，请知悉";
                    Message::addMessage(Message::CUSTOMER_TYPE, $v['id'], $staffList[$v['staff_member_id']], $this->auth->id, $content);
                }

            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success();
        } else {
            $this->error(__('操作失败'));
        }
        
    }
}
